package com.xingshang.service.impl;

import cn.hutool.core.bean.BeanUtil;
import cn.hutool.crypto.digest.DigestUtil;
import com.baomidou.mybatisplus.core.conditions.query.QueryWrapper;
import com.baomidou.mybatisplus.core.metadata.IPage;
import com.baomidou.mybatisplus.core.toolkit.StringUtils;
import com.baomidou.mybatisplus.extension.plugins.pagination.Page;
import com.baomidou.mybatisplus.extension.service.impl.ServiceImpl;
import com.xingshang.constant.FileLocationConstant;
import com.xingshang.exception.MallException;
import com.xingshang.model.dto.UserDto;
import com.xingshang.model.po.Admin;
import com.xingshang.model.po.User;
import com.xingshang.service.AdminService;
import com.xingshang.service.UserService;
import com.xingshang.mapper.UserMapper;
import com.xingshang.util.FileStorageUtilFactory;
import com.xingshang.util.MinioUtil;
import com.xingshang.util.RedisService;
import lombok.RequiredArgsConstructor;
import org.springframework.stereotype.Service;
import org.springframework.util.DigestUtils;
import org.springframework.web.multipart.MultipartFile;
import java.math.BigDecimal;
import java.time.LocalDateTime;
import java.util.Date;
import java.util.List;

import static com.xingshang.exception.CommonError.USER_HAS_EXIST;


/**
 * @author 87547
 * @description 针对表【wn_user】的数据库操作Service实现
 * @createDate 2025-04-01 08:37:17
 */
@Service
@RequiredArgsConstructor
public class UserServiceImpl extends ServiceImpl<UserMapper, User>
        implements UserService {
    public static long freezeTime = 60;//冻结时间
    private final UserMapper userMapper;
    private final AdminService adminService;
    private final RedisService redisService;
    private final FileStorageUtilFactory fileStorageUtilFactory;
    private final MinioUtil minioUtil;

    @Override
    public User login(String account, String password) {
        Admin admin = adminService.login(account, password);
        if (BeanUtil.isNotEmpty(admin)) {

            return User.builder()
                    .account(account)
                    .password(DigestUtils.md5DigestAsHex(password.getBytes()))
                    .build();
        }
        User user = lambdaQuery().eq(User::getAccount, account).one();

        if (BeanUtil.isNotEmpty(user)) {
            String s = DigestUtils.md5DigestAsHex(password.getBytes());
            if (s.equals(user.getPassword())) {

                System.out.println(user.getStatus());
                if(user.getStatus().equals("0"))//0冻结2黑名单
                {
                    Date now = new Date();
                    Date oldTime = user.getLastLoginTime();
                    System.out.println(now.getTime());
                    System.out.println(oldTime.getTime());
                    System.out.println(now.getTime() - oldTime.getTime());
                    if((now.getTime() - oldTime.getTime())/ 1000 <= freezeTime * 60)
                    {

                        return null;
                    }
                }
                if(user.getStatus().equals("2"))//0冻结2黑名单
                {
                        return null;
                }
                user.setLastLoginTime(new Date());
                user.setStatus("1");
                userMapper.updateById(user);
                return user;
            } else {
                return null;
            }
        }
        return null;
    }

    @Override
    public IPage<User> findByPage(int page, int pageSize, QueryWrapper<User> queryWrapper) {
        String cacheKey = generateCacheKey(page, queryWrapper);
//        redisService.clearUserCache();

        IPage<?> cachedData = redisService.getUserPage(cacheKey);
        if (cachedData != null) {
//            log.info("命中缓存: {}", cacheKey);
            return (IPage<User>) cachedData;
        }

        IPage<User> pageResult = new Page<>(page, pageSize);
        IPage<User> result = userMapper.selectPage(pageResult, queryWrapper);

        redisService.cacheUserPage(cacheKey, result);
        return result;
    }

    /**
     * 生成包含查询条件的缓存key
     */
    private String generateCacheKey(int page, QueryWrapper<User> queryWrapper) {
        StringBuilder keyBuilder = new StringBuilder(RedisService.USER_PAGE_PREFIX)
                .append("page:").append(page);

        String sqlSegment = queryWrapper.getCustomSqlSegment();
        if (StringUtils.isNotBlank(sqlSegment)) {
            keyBuilder.append(":query:").append(DigestUtil.md5Hex(sqlSegment));
        }

        queryWrapper.getParamNameValuePairs().forEach((k, v) -> {
            if (v != null) {
                keyBuilder.append(":").append(k).append(":").append(v);
            }
        });

        return keyBuilder.toString();
    }
    @Override
    public String insertUser(UserDto userDto) throws Exception {
        User userByAccount = lambdaQuery().eq(User::getAccount, userDto.getAccount()).one();
        System.out.println("userByAccount = " + userByAccount);
        if (BeanUtil.isNotEmpty(userByAccount)) {
            MallException.cast(USER_HAS_EXIST);
        }
        String path = this.saveAvatar(userDto.getAvatar());

        boolean save = save(User.builder()
                .account(userDto.getAccount())
                .password(DigestUtil.md5Hex(userDto.getPassword()))
                .email(userDto.getEmail())
                .telphone(userDto.getTelphone())
                .avatar(path)
                .points(0)
                .money(BigDecimal.valueOf(0.0))
                .regTime(new Date())
                .status("1")
                .build());
        if (!save)
        {
            return "注册失败";
        }
        return "success";
    }

    @Override
    public String saveAvatar(MultipartFile avatarFile) throws Exception {
        String originalFilename = avatarFile.getOriginalFilename();
        String fileName = minioUtil.generateFileName(originalFilename);

        // 返回文件URL
        return fileStorageUtilFactory.getStorageUtil().uploadFile(avatarFile, fileName, FileLocationConstant.USER_AVATAR_PHOTOS_PATH);

    }

    @Override
    public List<User> getAllUsers() {
        return userMapper.selectList(null);
    }


    @Override
    public boolean freezeUser(Long userId) {
        User user = getById(userId);
        if (user == null) {
            return false;
        }
        user.setStatus("0"); // 冻结状态码为0
        userMapper.updateById(user);
        return updateById(user);
    }

    @Override
    public boolean unfreezeUser(Long userId) {
        User user = getById(userId);
        if (user == null) {
            return false;
        }
        user.setStatus("1"); // 正常状态码为1
        userMapper.updateById(user);
        return updateById(user);
    }

    @Override
    public boolean addToBlacklist(Long userId) {
        User user = getById(userId);
        if (user == null) {
            return false;
        }
        user.setStatus("2"); // 黑名单状态码为2
        userMapper.updateById(user);
        return updateById(user);
    }

    @Override
    public boolean removeFromBlacklist(Long userId) {
        User user = getById(userId);
        if (user == null) {
            return false;
        }
        user.setStatus("1"); // 移出黑名单后恢复为正常状态
        userMapper.updateById(user);
        return updateById(user);
    }

    @Override
    public boolean deleteUser(Long userId) {
        return removeById(userId);
    }

}






